Imports Microsoft.VisualBasic

Public Enum CodeTypeEnum
    VB2005
    CS2005
End Enum

Public Enum ViewTypeEnum
    GridView
    Repeater
    CodeBehind
End Enum

Public Enum EditKeyPassingEnum
    Request
    Session
    Inline
End Enum

Public Enum DevelopmentMode
    Production
    Development
End Enum

Public Enum PagingEnum
    None
    Basic
    HighSpeed
End Enum

Public Enum CommentLevelEnum
    None
    Basic
    Verbose
End Enum
'Public 

Public Class RawCreateScript

    Public DevelopmentMode As DevelopmentMode = DevelopmentMode.Production
    Public ClassNamePrefix As String = ""

    Public IsAddImports As Boolean
    Public ProjectName As String
    Public GenNumber As Integer
    Public CodeType As CodeTypeEnum

    Public ViewType As ViewTypeEnum
    Public ConnectionStringMethod As String
    Public ConnectionString As String

    '    Public Paging As String
    Public Sorting As Boolean = False

    Private mEditKeyPassing As EditKeyPassingEnum

    Public Property EditKeyPassing() As EditKeyPassingEnum
        Get
            Return mEditKeyPassing
        End Get
        Set(ByVal value As EditKeyPassingEnum)
            mEditKeyPassing = value
        End Set
    End Property


    'Public Function ParameterGroupColumnName() As String
    '    ParameterGroupColumnName = PCGColumn.StaticSafeParameterName(GroupColumnName)
    'End Function

    Public ReadOnly Property IsAnyColumnDate() As Boolean
        Get
            For Each c As PCGColumn In Columns
                Select Case c.DataType.ToUpper
                    Case "DATETIME", "SMALLDATETIME", "TIMESTAMP"
                        Return True
                End Select
            Next
            Return False
        End Get
    End Property


    Public ReadOnly Property IsAnyColumnDateUsingDateTimePicker() As Boolean
        Get
            For Each c As PCGColumn In Columns
                Select Case c.DataFormat.ToUpper
                    Case "DATETIME"
                        Return True
                End Select
            Next
            Return False
        End Get
    End Property

    Public ReadOnly Property IsAnyColumnSearchable() As Boolean
        Get
            For Each c As PCGColumn In Columns
                If c.Search <> "None" Then
                    Return True
                End If
            Next
            Return False
        End Get
    End Property

    Private mAutoNumberColumn As String
    Public Property AutoNumberColumn() As String
        Get
            Return mAutoNumberColumn
        End Get
        Set(ByVal value As String)
            mAutoNumberColumn = value
        End Set
    End Property

    Private mPrimaryKeyName As String
    Public Property PrimaryKeyName() As String
        Get
            Return mPrimaryKeyName
        End Get
        Set(ByVal value As String)
            mPrimaryKeyName = value
        End Set
    End Property

    Public ReadOnly Property ColumnList() As String
        Get
            Dim List As String = ""
            For Each Column As PCGColumn In Me.Columns
                If List.Length > 0 Then
                    List = List & ", "
                End If
                List = List & Column.ColumnName
            Next
            Return List
        End Get
    End Property

    Public ReadOnly Property ColumnListSelectSyntax() As String
        Get
            Dim List As String = ""
            For Each Column As PCGColumn In Me.Columns
                If List.Length > 0 Then
                    List = List & ", "
                End If
                List = List & Column.ColumnName
            Next
            Return List
        End Get
    End Property

    Private mDatabaseName As String
    Public Property DatabaseName() As String
        Get
            Return mDatabaseName
        End Get
        Set(ByVal value As String)
            mDatabaseName = value
        End Set
    End Property


    Private mSchemaName As String
    Public Property SchemaName() As String
        Get
            Return mSchemaName
        End Get
        Set(ByVal value As String)
            mSchemaName = value
        End Set
    End Property


    Private mTableName As String
    Public Property TableName() As String
        Get
            Return mTableName
        End Get
        Set(ByVal value As String)
            mTableName = value
        End Set
    End Property

    Public ReadOnly Property OutputFileName() As String
        Get

            Return PCGColumn.StaticSafeParameterName(mTableName & Me.ClassNamePrefix)
        End Get

    End Property

    Public ReadOnly Property ClassName() As String
        Get
            Return PCGColumn.StaticSafeParameterName(mTableName & Me.ClassNamePrefix)
        End Get

    End Property


    Public Function SafeTableName() As String
        Return PCGColumn.StaticSafeParameterName(TableName)
    End Function

    Private mSchema As String
    Public Property Schema() As String
        Get
            Return mSchema
        End Get
        Set(ByVal value As String)
            mSchema = value
        End Set
    End Property

    Public Columns As ArrayList

    Public Sub New()
        Columns = New ArrayList
    End Sub


    Public Sub New(ByVal sql As String)
        Columns = New ArrayList

        Dim PastedText As String = sql
        PastedText = PastedText.Replace(vbTab, "")
        Dim Lines() As String = Split(PastedText, vbCrLf)

        For Each Line As String In Lines
            Dim Items() As String = Split(Line.Trim, " ")

            If Items.Length > 0 Then
                Select Case Items(0).Trim.ToUpper
                    Case "USE"
                        DatabaseName = TrimBraces(Items(1))

                    Case "CREATE"
                        Dim SchemaTablename As String = Items(2).Trim("(")
                        Dim s() As String = Split(SchemaTablename, ".")
                        If s.Length = 2 Then
                            TableName = TrimBraces(s(1))
                            Schema = TrimBraces(s(0))
                        ElseIf s.Length = 1 Then
                            TableName = TrimBraces(s(0))

                        Else
                            Throw New Exception("Unknown error CREATE")
                        End If
                End Select
            End If
        Next

        For Each Line As String In Lines
            If ContainsDataType(Line) Then
                Dim Column As New PCGColumn(Line)
                Columns.Add(Column)
            End If
        Next

        ' Search for primary key
        Dim PKS As String = PastedText
        Dim CurrentLength = 0
        PKS = "" & Replace(PKS, vbCrLf, " ")
        Do While PKS.Length <> CurrentLength
            CurrentLength = PKS.Length
            PKS = Replace(PKS, "  ", " ")
        Loop

        Dim PKStart As Long = InStr(PKS, "primary key", CompareMethod.Text)
        If PKStart > 0 Then
            Dim ParenthesisOpen As Long = InStr(PKStart, PKS, "(", CompareMethod.Binary)
            If ParenthesisOpen > 0 Then
                ParenthesisOpen = ParenthesisOpen + 1
                Dim ParenthesisClose As Long = InStr(ParenthesisOpen, PKS, ")", CompareMethod.Binary)
                If ParenthesisClose > 0 Then
                    Dim SearchString = Mid(PKS, ParenthesisOpen, ParenthesisClose - ParenthesisOpen).Trim
                    Dim NextSpace As Integer = InStr(SearchString, " ", CompareMethod.Binary)
                    If NextSpace > 0 Then
                        Dim PK As String = Left(SearchString, NextSpace)
                        PK = TrimBraces(PK).Trim

                        If PK.Length > 0 Then
                            For Each column As PCGColumn In Columns
                                If column.ColumnName.ToUpper = PK.ToUpper Then
                                    column.IsPrimaryKey = True
                                End If
                            Next
                        End If
                    End If
                End If

            End If
        End If
    End Sub

    Public Sub AddColumn(ByVal ColumnName As String, ByVal DataType As String, ByVal AllowNulls As Boolean, ByVal Length As String, ByVal DefaultValue As String, ByVal IsDisplayColumn As Boolean, ByVal IsIdentity As Boolean, ByVal IsPrimaryKey As Boolean, ByVal DisplayReadOnly As Boolean, ByVal DisplayInGrid As Boolean, ByVal Search As String, ByVal LinkTableName As String, ByVal LinkTableKey As String, ByVal LinkTableValue As String, ByVal DataFormat As String)
        Dim Column As New PCGColumn
        Column.DataFormat = DataFormat
        Column.ColumnName = ColumnName
        Column.DataType = DataType
        Column.AllowNulls = AllowNulls
        Column.Length = Length
        Column.DefaultValue = DefaultValue
        Column.IsDisplayColumn = IsDisplayColumn
        Column.IsIdentity = IsIdentity
        Column.IsPrimaryKey = IsPrimaryKey
        Column.DisplayReadOnly = DisplayReadOnly
        Column.DisplayInGrid = DisplayInGrid
        If Search.Length = 0 Then
            Column.Search = "None"
        Else
            Column.Search = Search
        End If
        'Debug.Print("AddColumn - " & Search)

        Column.LinkTableName = LinkTableName
        Column.LinkTableKey = LinkTableKey
        Column.LinkTableValue = LinkTableValue
        Columns.Add(Column)

        If DataType.ToUpper = "AUTONUMBER" Then
            mAutoNumberColumn = ColumnName
        End If

        If IsIdentity Then
            mAutoNumberColumn = ColumnName
        End If

    End Sub

    Private Function ContainsDataType(ByVal s As String) As Boolean
        Dim Items As ArrayList = Support.SplitList(s, "[] )(")
        For Each item As Object In Items
            Select Case UCase(item)
                Case "BIGINT", "BINARY", "BIT", "CHAR", "MONEY"
                    Return True
                Case "DATETIME", "DECIMAL", "FLOAT", "IMAGE", "INT"
                    Return True
                Case "NCHAR", "NTEXT", "NUMERIC", "NVARCHAR", "REAL"
                    Return True
                Case "SMALLDATETIME", "SMALLINT", "SMALLMONEY", "SQL_VARIANT"
                    Return True
                Case "TEXT", "TIMESTAMP", "TINYINT", "UNIQUEIDENTIFIER", "VARBINARY"
                    Return True
                Case "VARCHAR"
                    Return True
            End Select
        Next
        Return False
    End Function

    Private Function TrimBraces(ByVal s As String) As String
        If s.Length > 2 Then
            TrimBraces = Replace(s, "[", "")

            TrimBraces = Replace(TrimBraces, "]", "")
        Else
            TrimBraces = s
        End If
    End Function

    Public Function TableNameSpaceAfterCapitalLetter() As String
        TableNameSpaceAfterCapitalLetter = ""
        If UCase(TableName) = TableName Then
            TableNameSpaceAfterCapitalLetter = TableName
        Else
            Dim FirstChar As Boolean = True
            For Each c As Char In TableName
                If FirstChar Then
                    TableNameSpaceAfterCapitalLetter = c
                    FirstChar = False
                Else
                    If Char.IsUpper(c) Then
                        TableNameSpaceAfterCapitalLetter = TableNameSpaceAfterCapitalLetter & " " & c
                    Else
                        TableNameSpaceAfterCapitalLetter = TableNameSpaceAfterCapitalLetter & c
                    End If
                End If
            Next
        End If
    End Function

    'viewtype -    GridView,     Repeater,    CodeBehind
    Public Sub New(ByVal TableName As String, ByVal dt As DataTable, ByVal ConnectionStringMethod As String, ByVal ConnectionString As String, ByVal ViewType As String, ByVal IsAddImports As Boolean, ByVal CodeType As String, ByVal ProjectName As String, ByVal EditKeyPassing As String, ByVal CommentLevel As Long, ByVal Paging As String, ByVal Sorting As Boolean, ByVal ClassNamePrefix As String, ByVal SchemaName As String)
        Me.TableName = TableName
        Me.SchemaName = SchemaName
        Me.ClassNamePrefix = ClassNamePrefix
        Columns = New ArrayList
        For Each row As DataRow In dt.Rows
            AddColumn(row("ColumnName"), row("DataType"), row("AllowNulls"), row("ColumnSize"), "", row("ShowInDetailView"), row("IsIdentity"), False, False, row("ShowInMasterView"), row("SearchType").ToString, row("LinkTableName").ToString, row("LinkTableKey").ToString, row("LinkTableValue").ToString, row("DataFormat").ToString)
        Next

        'new
        Me.ConnectionStringMethod = ConnectionStringMethod
        Me.ConnectionString = ConnectionString

        Select Case ViewType
            Case "GridView"
                Me.ViewType = ViewTypeEnum.GridView
            Case "Repeater"
                Me.ViewType = ViewTypeEnum.Repeater
            Case "CodeBehind"
                Me.ViewType = ViewTypeEnum.CodeBehind
        End Select

        Me.IsAddImports = IsAddImports

        Select Case CodeType
            Case "VB2005"
                Me.CodeType = CodeTypeEnum.VB2005
            Case "CS2005"
                Me.CodeType = CodeTypeEnum.CS2005
        End Select

        Me.ProjectName = ProjectName
        Select Case EditKeyPassing
            Case "Request"
                Me.EditKeyPassing = EditKeyPassingEnum.Request
            Case "Session"
                Me.EditKeyPassing = EditKeyPassingEnum.Session
            Case "Inline"
                Me.EditKeyPassing = EditKeyPassingEnum.Inline
        End Select

        Me.CommentLevel = CommentLevel
        Select Case Paging.ToUpper
            Case "BASIC"
                Me.Paging = PagingEnum.Basic

            Case "HIGHSPEED"
                Me.Paging = PagingEnum.HighSpeed

            Case Else
                Me.Paging = PagingEnum.None

        End Select

        Me.Sorting = Sorting

        Select Case CommentLevel
            Case -1
                Me.CommentLevel = CommentLevelEnum.None
            Case 1
                Me.CommentLevel = CommentLevelEnum.Basic
            Case 2
                Me.CommentLevel = CommentLevelEnum.Verbose
        End Select


    End Sub

    Private mPaging As PagingEnum
    Public Property Paging() As PagingEnum
        Get
            Return mPaging
        End Get
        Set(ByVal value As PagingEnum)
            mPaging = value
        End Set
    End Property


    Private mCommentLevel As CommentLevelEnum
    Public Property CommentLevel() As CommentLevelEnum
        Get
            Return mCommentLevel
        End Get
        Set(ByVal value As CommentLevelEnum)
            mCommentLevel = value
        End Set
    End Property



End Class
